#!/usr/bin/python3
import os
from .Entity import Entity
from utils import String_Util, My_Util2
from wrappers.OpenAPI_Wrapper import (
    get_field_annotation,
    get_api_model_annotation,
    get_includes,
)


class Model_Query:
    """
    实体存在性条件类模型
    """

    def __init__(self, context, entity: Entity) -> None:
        self.context = context
        self.entity: Entity = entity
        self.prefix: str = self.entity.table_name.split("_")[0].lower()
        self.ignores = String_Util.ignore_fields
        self.my_util2 = My_Util2.My_Util(self.context)

    def code_includes(self):
        package = self.entity.package
        entity_name = self.entity.name
        includes = list()

        includes.append(f"""import {package}.internal.query.exists.{entity_name}BaseExists;""")
        includes += get_includes("model")
        includes += get_includes("field")
        includes.append(f"""import lombok.Data;""")
        includes.append(f"""import lombok.EqualsAndHashCode;""")
        includes.append(f"""import lombok.ToString;""")
        includes.append(f"""import lombok.experimental.Accessors;""")
        includes.append(f"""import java.util.List;""")
        includes = self.my_util2.sort_import_order(includes)
        return "\r".join(includes)

    def code_id_list(self):
        return f"""
    {get_field_annotation(f"""description = \"主键列表\"""")}
    private List<Long> idList;"""

    def code_fields(self):
        field_codes = list()
        for field in self.entity.fields:
            if field.ignore(self.ignores):
                continue
            field_codes.append(field.code())
        return field_codes

    def save_file(self, dir):
        prefix = self.prefix
        _target_dir = os.path.join(dir, prefix, "query", "exists")
        if not os.path.exists(_target_dir):
            os.makedirs(_target_dir)
        with open(
            os.path.join(_target_dir, "{}Exists.java".format(self.entity.name)),
            mode="w",
            encoding="utf-8",
        ) as f:
            f.write(self.code())

    def code(self):
        package = self.entity.package
        entity_name = self.entity.name
        comment = self.entity.comment
        author = self.entity.author
        prefix = self.prefix

        includes = self.code_includes()
        code_id_list = self.code_id_list()

        return f"""package {package}.{prefix}.query.exists;

{includes}

/**
 * <p>
 * {comment}存在性条件类
 * </p>
 *
 * @author {author}
 */
@EqualsAndHashCode(callSuper = true)
@Data
@Accessors(chain = true)
@ToString(callSuper = true)
{get_api_model_annotation(f"""{entity_name}Exists""", comment)}
public class {entity_name}Exists extends {entity_name}BaseExists {"{"}
{code_id_list if len(code_id_list) > 0 else ''}
{"}"}
"""
